package com.wsoft.sms.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.core.service.CommonOrgService;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.core.vo.OrganizationVO;
import com.wsoft.entity.BaseEntity;
import com.wsoft.enums.MsgTypeEnum;
import com.wsoft.enums.PublishStatusEnum;
import com.wsoft.sms.entity.SmsMessageEntity;
import com.wsoft.sms.entity.SmsTemplateEntity;
import com.wsoft.sms.mapper.SmsMessageMapper;
import com.wsoft.sms.mapper.SmsTemplateMapper;
import com.wsoft.sms.query.message.MessageListQuery;
import com.wsoft.vo.LoginUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Zhang gukai
 * @Date 2025/1/3 14:32
 */
@Slf4j
@Service
public class MessageManager extends ServiceImpl<SmsMessageMapper, SmsMessageEntity> {

    @Resource
    private CommonOrgService orgService;

    /**
     * 管理端 查询 分页
     * @param listQuery
     * @param isUser
     * @return List<SmsMessageEntity>
     */
    public List<SmsMessageEntity> listMessage(MessageListQuery listQuery, boolean isUser, Long messageId) {
        QueryWrapper<SmsMessageEntity> query = new QueryWrapper<>();
        query.lambda().eq(SmsMessageEntity::getClientType, "web");
        if (isUser) {
            //用户端 只查询已发布的,发布时间排序
            query.lambda().eq(SmsMessageEntity::getSendStatus, PublishStatusEnum.PUBLISH.getType());

            LoginUserVO userVO = LoginUserUtil.getUserInfo().getLoginUserVO();
            //当前登录人组织
            Long curOrgId = userVO.getLoginOrgId();
            //当前登录人岗位
            Long curPostId = userVO.getCurPostId();
            //当前登录人级别
            Long curLevelId = userVO.getLevelId();
            //当前登录人id
            Long curUserId = userVO.getId();

            List<OrganizationVO> parentOrg = orgService.getParentOrg(curOrgId);
            List<Long> orgIdList = new ArrayList<>();
            orgIdList.add(curOrgId);
            if (CollUtil.isNotEmpty(parentOrg)) {
                orgIdList.addAll(parentOrg.stream().map(OrganizationVO::getOrgId).collect(Collectors.toList()));
            }
            //权限
            query.lambda().and(wrapper ->
                    wrapper.nested(nestedWrapper -> {
                        // 指定组织
                        for (Long orgId : orgIdList) {
                            nestedWrapper.or(nestedOrWrapper ->
                                    nestedOrWrapper.eq(SmsMessageEntity::getMsgType, MsgTypeEnum.ORG.getType())
                                            .apply("FIND_IN_SET({0}, msg_ids)", orgId) // 使用 FIND_IN_SET 判断是否包含当前组织 ID
                            );
                        }
                    }).or(nestedWrapper ->
                            //指定岗位
                            nestedWrapper.eq(SmsMessageEntity::getMsgType, MsgTypeEnum.POST.getType())
                                    .like(SmsMessageEntity::getMsgIds, curPostId)
                    ).or(nestedWrapper ->
                            //指定级别
                            nestedWrapper.eq(SmsMessageEntity::getMsgType, MsgTypeEnum.LEVEL.getType())
                                    .like(SmsMessageEntity::getMsgIds, curLevelId)
                    ).or(nestedWrapper -> {
                        //指定用户
                        nestedWrapper.or(nestedOrWrapper ->
                                nestedOrWrapper.eq(SmsMessageEntity::getMsgType, MsgTypeEnum.MEMBER.getType())
                                        .apply("FIND_IN_SET({0}, msg_ids)", curUserId)
                        );
                    })
            );
            query.lambda()
                    .orderByDesc(SmsMessageEntity::getSendTime);
        } else {
            //后台端按创建时间排序
            query.lambda().like(StrUtil.isNotBlank(listQuery.getTitle()), SmsMessageEntity::getTitle, listQuery.getTitle())
                    .eq(null != listQuery.getSendOrgId(), SmsMessageEntity::getSendOrgId, listQuery.getSendOrgId())
                    .eq(null != listQuery.getSendMemberId(), SmsMessageEntity::getSendMemberId, listQuery.getSendMemberId())
                    .eq(StrUtil.isNotBlank(listQuery.getSendStatus()), SmsMessageEntity::getSendStatus, listQuery.getSendStatus())
                    .eq(StrUtil.isNotBlank(listQuery.getPriority()), SmsMessageEntity::getPriority, listQuery.getPriority())
                    .eq(StrUtil.isNotBlank(listQuery.getWarnType()), SmsMessageEntity::getWarnType, listQuery.getWarnType())
                    .eq(null !=listQuery.getType(), SmsMessageEntity::getType, listQuery.getType())
                    .ge(StrUtil.isNotBlank(listQuery.getSendTimeBegin()), SmsMessageEntity::getSendTime, listQuery.getSendTimeBegin())
                    .le(StrUtil.isNotBlank(listQuery.getSendTimeEnd()), SmsMessageEntity::getSendTime, listQuery.getSendTimeEnd())
                    .orderByDesc(BaseEntity::getCreateTime);
        }
        List<SmsMessageEntity> list = list(query);
        if (null != messageId) {
            //messageId,则判断 ==> 当前是否有权限查看这个消息,如果返回有值,则有权限,如果返回list为空,则无权限
            list = list.stream().filter(item -> item.getId().equals(messageId)).collect(Collectors.toList());
        }
        return list;
    }

    public List<SmsMessageEntity> getPublishMessages(){
        QueryWrapper<SmsMessageEntity> query = new QueryWrapper<>();
        query.lambda().eq(SmsMessageEntity::getSendStatus, PublishStatusEnum.WAIT_PUBLISH.getType())
                .le(SmsMessageEntity::getSendTime, LocalDateTime.now());
        return list(query);
    }
}
